<template>
  <FullScreenDialog :title="dialog.title" :visible="dialog.visible" v-if="dialog.visible" :showFooter="dialog.showFooter"
    @onClose="onClose" @onConfirm="confirm">
    <template v-slot:content>
      <!-- 内容组件 -->
      <div class="Documen_container">
        <div class="left-img">
          <el-scrollbar>
            <div class="img-height">
              <!-- 需要一个canvas操作 1数据 2 事件回传 3 添加input -->
              <ImgCanVas ref="RefImgCanVas"
                :img="pdfShowDate.img_info && pdfShowDate.img_info[0] && pdfShowDate.img_info[0].imageBase64"
                :img-obj="pdfShowDate.img_info && pdfShowDate.img_info[0] && pdfShowDate.img_info[0]"
                :record-list="pdfShowDate.recordList" @inputPos="inputPos" :type="pdfShowDate.type">
              </ImgCanVas>
            </div>
            <div class="img-page">
              <el-button>{{ pdfShowDate.search.pageNumber }}/{{ pdfShowDate.numPages }}</el-button>
              <el-button type="primary" @click="btnPre" :disabled="pdfShowDate.search.pageNumber === 1">上一页</el-button>
              <el-button type="primary" @click="btnNext"
                :disabled="pdfShowDate.search.pageNumber === pdfShowDate.numPages">下一页</el-button>
            </div>
          </el-scrollbar>
        </div>
        <div class="center-mark">
          <el-scrollbar>
            <!-- 1 如何传递数据 2 如何保存数据 3 修改数据 4 其他操作 -->
            <!-- {{  pdfShowDate.img_info[0].commentsDTOs}} -->
            <MarkInput :checkList="store.getChecks" @newinput="newinput" :limits="pdfShowDate.limits"
              :markLoading="pdfShowDate.markLoading" :DocumentData="DocumentData" @titleChange="titleChange"
              @newSave="newSave" @btnMarkDel="btnMarkDel" @getAbnormalList="getAbnormalList"
              :AuditPageList="AuditPageList"
              :annotate="pdfShowDate.img_info && pdfShowDate.img_info[0] && pdfShowDate.img_info[0].commentsDTOs">
            </MarkInput>
          </el-scrollbar>
        </div>
        <div class="right-analysis">
          <el-scrollbar>
            <div class="ApproTop">
              <topSalary v-for="item in store.getChecks" :key="item.id" :checked="getTsIds.includes(item.id)" :item="item"
                @btnApproSalary="btnApproSalary" />
            </div>
            <div class="ApproTop">
              <tableCheck :analyseList="store.getAnalysiss"></tableCheck>
            </div>
            <div class="abnorlmal-table">
              <!-- 1 展示 2 删除联动 3 刷新 -->
              <el-scrollbar>
                <AbnormalTable ref="RefAbnormalTable" @lookAbnormalDetail="lookAbnormalDetail"></AbnormalTable>
              </el-scrollbar>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <Abnormal ref="RefAbnormal"></Abnormal>
    </template>
  </FullScreenDialog>
</template>

<script setup lang='ts'>
import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import ImgCanVas from './components/ImgCanvas.vue'
import MarkInput from './components/MarkInput.vue'
import AbnormalTable from './components/abnormalTable.vue'
import useDialog from '@/hooks/useDialog';
import useInstance from '@/hooks/useInstance';
import { recordGetRecordApi, getImageUrlApi, recordSaveApi, recordRemoveApi } from '@/api/ReviewBusiness/01Project/project'
import { getArrayToHis } from '@/utils/index'
import { checkAnalysisStore } from '@/store/analysis'
import abnormalDetail from '@/view/02ReviewBusinessMan/02ReviewManagement/composables/abnormalDetail'
const { RefAbnormal, lookDetail, assignBtn1 } = abnormalDetail()

const props = defineProps({
  DocumentData: {
    type: Object,
    default: () => { }
  },
  AuditPageList: {
    type: Array,
    default: () => []
  }
})
// 使用
const RefAbnormalTable = ref()
const store = checkAnalysisStore()
const RefImgCanVas = ref<any>(null)
const lookAbnormalDetail = (row) => {
  // 查看异常单详情的东西
  lookDetail(row)
}
const pdfShowDate = reactive({
  // 数据怎么处理 1 查询数据 2 canvas数据 3 mark数据 4 analysis 
  fileDate: {},
  search: {
    filesId: '',
    pageNumber: 1
  },
  limits: false,
  // img数据
  recordList: [],
  imageId: '',
  img_info: [] as any,
  numPages: 0,
  type: 'R',
  markLoading: false
})
const { dialog, onShow } = useDialog()
const { global, proxy } = useInstance();
const getAbnormalList = () => {
  RefAbnormalTable.value?.getAbnormalList()
}
const getTsIds = computed(() => {
  const checkAllList = store.getCheckLists
  return checkAllList.map(e => e.id)
})
const onClose = () => {
  RefImgCanVas.value?.clearCanvasDate()
  dialog.visible = false
  // 清空数据
  pdfShowDate.search = {
    filesId: '',
    pageNumber: 1
  }
  pdfShowDate.recordList = []
  pdfShowDate.limits = false
  pdfShowDate.imageId = ''
  pdfShowDate.numPages = 0
  pdfShowDate.type = 'R'
  pdfShowDate.fileDate = {}
  pdfShowDate.img_info = [],
  pdfShowDate.markLoading = false
}

const rowValue = ref()
const titleChange = async (e) => {
  store.setCheckAllList(e)
}
const btnApproSalary = (item) => {
  // this.$store.commit('common/setCheckAllList', item)
  store.setCheckAllList(item)
}
const newSave = () => {
  btnConfirm()
}
const btnMarkDel = (citem, index, jx) => {
  // const curNum = this.pageNum
  if (citem.recordId) {
    recordRemoveApi([citem.recordId])
  }
  console.log(citem, index, jx, 'del')
  // 1 删除数据 input 2 删除canvas的矩形框 3commentsDTOs 有问题
  pdfShowDate.img_info[0].commentsDTOs[index].splice(jx, 1)
  // 一个矩形对应多个数组 2 一个数组空了 ,就删除 - 再删除对应的矩形
  pdfShowDate.img_info[0]?.commentsDTOs?.map((item, index) => {
    // 数据为空 history怎么处理 需要重新排序
    console.log(!item.length)
    if (!item.length) {
      pdfShowDate.img_info[0].commentsDTOs.splice(index, 1)
      // 对应的矩形也需要删除
      // 只需要把数据重新传递过去然后渲染就好了
      nextTick(() => {
        if (RefImgCanVas.value) {
          // refs.newDraw(this.img_info[0].commentsDTOs)
          RefImgCanVas.value?.newDraw(pdfShowDate.img_info[0].commentsDTOs)
        }
      })
    }
  })
}
const btnPre = async () => {
  // 如何避免第一页和最后一页bug
  pdfShowDate.img_info = []
  RefImgCanVas.value?.clearCanvasDate()
  // 判断页码 上一页 
  await getFileImage({ filesId: rowValue.value.id, pageNumber: pdfShowDate.search.pageNumber - 1 }, false)
  let page = pdfShowDate.search.pageNumber
  page = page > 1 ? page - 1 : pdfShowDate.numPages
  pdfShowDate.search.pageNumber = page
  pdfShowDate.imageId = pdfShowDate.img_info[0].records[0].imageId
  if (pdfShowDate.img_info.length > 0) {
    nextTick(() => {
      RefImgCanVas.value?.initImage()
    })
  }
}
const btnNext = async () => {
  pdfShowDate.img_info = []
  RefImgCanVas.value?.clearCanvasDate()

  await getFileImage({ filesId: rowValue.value.id, pageNumber: pdfShowDate.search.pageNumber + 1 }, false)
  let page = pdfShowDate.search.pageNumber
  page = page < pdfShowDate.numPages ? page + 1 : 1
  pdfShowDate.search.pageNumber = page
  pdfShowDate.imageId = pdfShowDate.img_info[0].records[0].imageId
  if (pdfShowDate.img_info.length > 0) {
    nextTick(() => {
      RefImgCanVas.value?.initImage()
    })
  }
}
// 保存
const confirm = () => { }
const show = async (type: string, row?: any) => {
  rowValue.value = JSON.parse(JSON.stringify(row))
  // 数据过来了 怎么处理 调用接口 获取文件流呗 还有一个问题没得文件怎么处理这个数据
  // 发送请求

  dialog.title = row.fileName
  dialog.showFooter = false
  await getFileList(row)
  const res = await getFileImage({ filesId: row.id, pageNumber: 1 }, false)
  if (!(res.data.length > 0)) {
    global.$message({ message: '数据处理中 请等待...', type: 'warning' })
    return true
  }

  store.getCheck(row.stageId)
  onShow()
  // 这个地方才可以获取dom数据 也就是再这个地方需要判断一哈 就好了
  if (pdfShowDate.img_info.length > 0) {
    nextTick(() => {
      RefImgCanVas.value?.initImage()
    })
  }
}
const getFileImage = async (row, flag?) => {
  const res: any = await recordGetRecordApi(row)
  if (res.code == 200 && res.data.length > 0) {
    //数据
    pdfShowDate.recordList = res.data
    console.log(pdfShowDate.recordList, '有数据 pdfShowDate.recordList');
    pdfShowDate.numPages = res.data[0].count
    const imagePath = res.data[0].imagePath
    pdfShowDate.imageId = res.data[0].imageId
    const path = imagePath.substring(8, imagePath.length)
    const file = await getImageUrl(path) as any
    const image = window.webkitURL.createObjectURL(new Blob([file], { type: 'image/png' }))
    const arr = getArrayToHis(res.data)
    const item = {
      imageBase64: `${image}`,
      page: pdfShowDate.search.pageNumber,
      fileId: pdfShowDate.search.filesId,
      commentsDTOs: arr,
      records: res.data
    }
    // 编辑需要
    if (flag) {
      pdfShowDate.img_info[0].commentsDTOs = arr
    } else {
      pdfShowDate.img_info.push({ ...item })
    }

  } else {
    console.log('没有数据');

    // 没有数据 全部清空啊数据
    pdfShowDate.recordList = []
    pdfShowDate.numPages = 0
    pdfShowDate.imageId = ''
    pdfShowDate.img_info = []
  }
  return res
}
const getImageUrl = async (path) => {
  return new Promise((resolve, reject) => {
    getImageUrlApi(path).then((res) => {
      resolve(res)
    }).catch((err) => {
      console.log(err);
      reject(err)
    })
  })
}
const getFileList = async (row?) => {
  pdfShowDate.fileDate = row
  pdfShowDate.search.filesId = row.id
  pdfShowDate.search.pageNumber = 1
}
defineExpose({
  show
})
const inputPos = (positions, index) => {
  console.log(positions, index, 'positions, index')
  // 点击选中的 分析项 1 点击删除 找到相同的分析项 是否唯一
  const ids = store.getAnalysiss // 这个name 等于 undefxxx 必定是没有选择，让其默认为 第一个 也就是 概念文档评价
  const tsList = {
    title: store.getCheckLists[0].name,//firstItem.name,
    titleDesc: '',
    distLeft: positions.left,
    distTop: positions.top,
    id: '',
    rectIndex: index,
    imageId: pdfShowDate.imageId,
    width: positions.width,
    height: positions.height
  }
  // // 还有一种情况就是 第二次添加再一个数组中 这个是第一次this.img_info[0].commentsDTOs.length
  // this.$set(this.img_info[0].commentsDTOs, this.img_info[0].commentsDTOs.length, this.tsList)
  pdfShowDate.img_info[0].commentsDTOs.push([{ ...tsList }])
}
const newinput = (item, index) => {
  const tsList = {
    title: store.getCheckLists[0].name,//firstItem.name,
    titleDesc: '',
    distLeft: item[0].distLeft,
    distTop: item[0].distTop,
    id: '',
    rectIndex: index,
    imageId: pdfShowDate.imageId,
    width: item[0].width,
    height: item[0].height
  }
  // 有问题 什么问题 就是添加了 突然消失了 什么原因 是焦点的问题嘛 ?
  // this.$set(this.img_info[0].commentsDTOs[index], this.img_info[0].commentsDTOs[index].length, tsList)
  pdfShowDate.img_info[0].commentsDTOs[index].push({ ...tsList })
}
const btnConfirm = async () => {
  pdfShowDate.markLoading = true
  let saveDate = [] as any
  const newArr = pdfShowDate.img_info[0].commentsDTOs.flat()
  newArr.map(item => {
    if (item.recordId) {
      saveDate.push({
        ...item,
        id: item.recordId
      })
    } else {
      //  if(item.titleDesc)
      saveDate.push(item)
    }
  })
  // 提交的数据 应该怎么处理 
  const res = await recordSaveApi(saveDate)
  if (res.code === 200) {
    saveDate = []
    // getAllFileImages(this.pageNum)
    await getFileImage({ filesId: rowValue.value.id, pageNumber: pdfShowDate.search.pageNumber }, true)
    nextTick(() => {
      pdfShowDate.markLoading = false
    })
  } else {
    // proxy.$message.error('保存失败')
  }
}
</script>
<style scoped lang='scss'>
.Documen_container {
  height: 100%;
  width: 100%;
  display: flex;
  overflow: auto;

  .left-img {
    // 设计一个A4 的框 然后滚动 padding 10px
    height: 100%;
    overflow: auto;
    position: relative;
    box-sizing: border-box;
    width: 834px;

    .img-page {
      position: fixed;
      height: 40px;
      width: 814px;
      bottom: 5px;
      // left: 10px;
      // right: 600px;
      // background-color: rgba(200, 200, 200, .5);
      border-radius: 5px;
      text-align: center;
      line-height: 40px;
    }

    // 怎么设计
    .img-height {
      margin: 10px;
      margin-bottom: 50px;
      width: 814px;
      // height: 8000px;
    }
  }

  .center-mark {
    width: 500px;
    height: 100%;
    overflow: auto;
    // background-color: pink;
  }

  .right-analysis {
    width: calc(100% - 1334px);
    height: 100%;
    position: relative;
    padding-left: 10px;

    .ApproTop {
      height: 120px;
      align-content: flex-start;
      flex-wrap: wrap;
      // background-color: pink;
      display: flex;
      overflow: auto;
    }

    .abnorlmal-table {
      position: absolute;
      width: 100%;
      height: calc(100% - 240px) !important;
    }
  }
}
</style>